package fr.emn.integration.synthese.controle;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import fr.emn.integration.synthese.abstraction.Cours;
import fr.emn.integration.synthese.abstraction.Eleve;
import fr.emn.integration.synthese.abstraction.ListeEleve;
import fr.emn.integration.synthese.presentation.*;

public class ControlJTableEleve extends Observable implements Observer,
		TableModelListener, MouseListener {

	private JTable tableEleve;
	private Cours modele;
	private ListeEleve eleves;
	private JLabel stat;
	private int taille;
	private float cumule;
	private Float notMax;
	private Float notMin;
	private float ecartype;
	private String etendue;
	private int compteur;
	private float mediane;
	private ArrayList<Float> listnotes;
	private int init;

	public ControlJTableEleve(Cours cours, JTable tableEleve, ListeEleve eleve,
			JLabel stat) {
		this.modele = cours;
		this.eleves = eleve;
		this.tableEleve = tableEleve;
		this.stat = stat;
		this.taille = 0;
		this.cumule = 0;
		this.notMax = (float) 0;
		this.notMin = (float) 0;
		this.ecartype = 0;
		this.etendue = null;
		this.mediane = 0;
		this.compteur = 0;
		this.listnotes = new ArrayList<Float>();
		this.init =0;
	}

	@Override
	public void tableChanged(TableModelEvent arg0) {
		// TODO Auto-generated method stub
		if(this.init == 0){
			this.init= 1;
			eleves.updateList();
			Iterator<Eleve> it = eleves.getList().iterator();
			Object[] donnee = null;
			
			while (it.hasNext()) {
				Eleve temp = it.next();
				donnee = new Object[] { temp.getNom(),
						temp.getPrenom(), temp.getMail(),
						temp.getGenre(), 0, false };
				((JTableEleveModel) tableEleve.getModel())
						.addRow(donnee);
				taille++;
			}
			this.tableEleve.repaint();

		}
		
		if (tableEleve.getRowCount() > 0
				&& modele.getEvaluationCourante() != -1 && modele.getEleveCourant() !=-1 && tableEleve.getSelectedRow()!=-1) {

				try {
					modele.saveNote(
							modele.getEvaluationCourante(),
							modele.getEleveCourant(),
							Float.parseFloat(tableEleve.getModel().getValueAt(tableEleve.getSelectedRow(), 4).toString()),
							Boolean.parseBoolean(tableEleve.getModel().getValueAt(tableEleve.getSelectedRow(), 5).toString()));
					
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println();
		
	}

	public void update(Observable o, Object message) {

		Integer iMessage = (Integer) message;
		

		if (iMessage == Cours.CHANGEMENT_EVAL_COURANTE
				|| iMessage == Cours.CHANGEMENT_GROUPE_COURANT
				|| iMessage == Cours.CHANGEMENT_MODULE_COURANT
				|| iMessage == Cours.CHANGEMENT_ELEVES) {

			while (tableEleve.getRowCount() > 0) {
				((JTableEleveModel) tableEleve.getModel()).removeRow(0);
			}

			eleves.updateList();

			if (eleves.getList() != null) {
				Iterator<Eleve> it = eleves.getList().iterator();
				Object[] donnee = null;
				if (modele.getEvaluationCourante() != -1) {
					while (it.hasNext()) {
						Eleve temp = it.next();
						donnee = new Object[] {
								temp.getNom(),
								temp.getPrenom(),
								temp.getMail(),
								temp.getGenre(),
								temp.getNote(modele.getEvaluationCourante()),
								temp.getDefinite(modele.getEvaluationCourante()) };
						listnotes.add((float) temp.getNote(modele
								.getEvaluationCourante()));

						((JTableEleveModel) tableEleve.getModel())
								.addRow(donnee);
						taille++;

						cumule = cumule
								+ temp.getNote(modele.getEvaluationCourante());
						compteur++;
					}
					Collections.sort(listnotes, Collections.reverseOrder());
					float moyenne = cumule / listnotes.size();

					float dispersion = 0;
					for (int i = 0; i < listnotes.size(); i++) {
						dispersion = dispersion + (listnotes.get(i) - moyenne)
								* (listnotes.get(i) - moyenne);
					}
					ecartype = (float) Math.sqrt(dispersion / taille);
					if (listnotes.size() > 0) {
						notMin = listnotes.get(listnotes.size() - 1);
						notMax = listnotes.get(0);
						etendue = "[" + String.valueOf(notMin) + ";"
								+ String.valueOf(notMax) + "]";

						if (taille % 2 != 0) {
							mediane = listnotes.get(((taille + 1) / 2) - 1);
						} else {
							float du = (float) taille;
							float norm = (du + 1) / 2;
							Integer cor = (taille + 1) / 2;
							if (norm > cor) {
								mediane = (listnotes.get(cor) + listnotes
										.get(cor - 1)) / 2;
							} else {
								mediane = (listnotes.get(cor - 1) + listnotes
										.get(cor - 2)) / 2;
							}
						}
					}
					ControlJLabelStat.setStat(taille, moyenne, etendue,
							ecartype, mediane);
				} else {
					while (it.hasNext()) {
						Eleve temp = it.next();
						donnee = new Object[] { temp.getNom(),
								temp.getPrenom(), temp.getMail(),
								temp.getGenre(), 0, false };
						((JTableEleveModel) tableEleve.getModel())
								.addRow(donnee);
						taille++;
					}
					ControlJLabelStat.setStat(taille, 0, etendue, ecartype,
							mediane);
				}

			}
		}
		taille = 0;
		cumule = 0;
		etendue = null;
		ecartype = 0;
		listnotes = new ArrayList<Float>();
		mediane = 0;
		compteur = 0;
		this.tableEleve.repaint();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		modele.setEleveCourant(modele.findEleveId(
				(String) tableEleve.getValueAt(tableEleve.getSelectedRow(), 0),
				(String) tableEleve.getValueAt(tableEleve.getSelectedRow(), 1)));
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

}
